import axios from 'axios'
import {Message} from 'element-ui'
import qs from 'qs'
import store from '@/store'

const service = axios.create({
  baseURL: 'https://impapi.wissdom.cn',
  withCredentials: false,
  timeout: 300000,
  paramsSerializer: function (params) {
    return qs.stringify(params, {arrayFormat: 'indices'})
  },
})

// request interceptor
service.interceptors.request.use(
  config => {
    let  token =window.localStorage.getItem("token")
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    config.transformRequest = [function (data) {
      return qs.stringify(data)
    }]
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    if (response.headers['content-disposition']) {
      const res = response
      return res
    } else {
      const res = response.data
      return res
    }
  },
  error => {
      if (error.response.hasOwnProperty("status") && error.response.status === 401) {
        //token过期了，记录token无效
        localStorage.removeItem('token')
        store.dispatch('changeToken','')
        store.dispatch('updateUser',null)        
      } else {
        Message({
          message: error.response.data.message ? error.response.data.message : '操作失败！',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject()
      }
  }
)

export default service
